import dayjs from "dayjs";
import fso from "@/utils/FileOperate/operate";
import getDeviceInfo from "./getDeviceInfo";
import { Module } from "./nativeModules";

/** 时分秒转成秒数, 举例: 01:10:05 => 3600 + 600 + 5 = 4205 */
export const timeToSecond = (time: string) => {
  if (time.indexOf(":") !== -1) {
    const [h, m, s] = time.split(":").map(e => Number(e));
    return h * 60 * 60 + m * 60 + s;
  } else {
    return 0;
  }
};

/** 获取当前时间, 默认格式: YYYY-MM-DD HH:mm:ss */
export const getFmtTime = (fmt = "YYYY-MM-DD HH:mm:ss", time = new Date()) => {
  return dayjs(time).format(fmt);
};

/** 修改本机的时间 */
export const setNativeDate = (timeStr: string) => {
  return new Promise<void>(async resolve => {
    try {
      fso.info("设置系统时间 :", timeStr);
      const isRoot = Module.isRoot();
      if (!isRoot) {
        fso.info("当前没有ROOT权限不设置时间");
        resolve();
        return;
      }
      const dayTime = dayjs(timeStr);
      const deviceInfo = await getDeviceInfo();
      const systemVersion = deviceInfo.systemVersion.charAt(0);
      fso.info("当前 Android 版本: ", deviceInfo.systemVersion);
      /* 判断版本系统 */
      if (systemVersion === "5") {
        const time = dayTime.format("YYYYMMDD.HHmmss");
        fso.info("Android 5修改系统时间: ", time);
        const res = await Module.setSystemTime(time);
        fso.info("修改时间响应: ", res);
      } else if (systemVersion === "7") {
        const time = dayTime.format("MMDDHHmmYYYY.ss");
        fso.info("Android 7修改系统时间: ", `date ${time} set`);
        const res = await Module.execShell(`date ${time} set`, true);
        fso.info("修改时间响应: ", res);
      } else {
        fso.info("未兼容时间修改的Android版本: ", deviceInfo.systemName, deviceInfo.systemVersion);
      }
    } catch (err) {
      fso.error("设置系统时间出错");
    } finally {
      resolve();
    }
  });
};
